package com.kexin.jbsg.guansdk;

import java.io.UnsupportedEncodingException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.kexin.jbsg.guansdk.interfaces.GuanSDK;
import com.kexin.jbsg.guansdk.model.KomLoginResponseData;
import com.kexin.jbsg.guansdk.utils.Base64;
import com.kexin.jbsg.guansdk.utils.Util;

public class LoginActivity extends Activity implements OnClickListener{
	public final static int VISIBLE_GONE=8;
	public final static int VISIBLE_VISIBLE=0;
	
	public static LoginActivity instance;
	EditText et_userAccount;
	EditText et_pwd;
	CheckBox cb_savePwd;
	Button btn_register;
	Button btn_login;
	Button btn_backGame;
	
	TextView tv_msg_userAccount;
	TextView tv_msg_password;
	
	public static final int[] byteFix = {2,4};
	public static final String key = "kom";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		this.setResult(KomSDKInfo.RESULT_CODE_LOGIN, intent);
		
		setContentView(R.layout.activity_login);
		btn_register = (Button) findViewById(R.id.login_btn_register);
		btn_register.setOnClickListener(this);
		btn_login = (Button) findViewById(R.id.login_btn_login);
		btn_login.setOnClickListener(this);
		btn_backGame = (Button) findViewById(R.id.login_backGame);
		btn_backGame.setOnClickListener(this);
		
		et_userAccount = (EditText) findViewById(R.id.login_userAccount);
		et_pwd = (EditText) findViewById(R.id.login_password);
		cb_savePwd = (CheckBox) findViewById(R.id.login_savePassword);
		
		tv_msg_userAccount = (TextView) findViewById(R.id.login_msg_userAccount);
		tv_msg_password = (TextView) findViewById(R.id.login_msg_password);
		
		//加载用户数据
		loadUserInfo();
		
		instance = this;
	}
	
	
	/**
	 * 加载用户数据
	 */
	public void loadUserInfo(){
		 SharedPreferences userInfo = getSharedPreferences("kom_ol_userInfo", 0); 
		 String userAccount = userInfo.getString("userAccount",null);
		 String password = userInfo.getString("password", null);
		 boolean savePassword = userInfo.getBoolean("savePassword", false);
		 if(savePassword){
			 cb_savePwd.setChecked(true);
			 if(userAccount!=null){
				 et_userAccount.setText(userAccount);
			 }
			 if(password!=null){
				 et_pwd.setText(decodePassword(password));
			 }
		 }else{
			 cb_savePwd.setChecked(false);
		 }
	}


	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.login_btn_register) {
			goRegister();
		} else if (id == R.id.login_btn_login) {
			normalLogin();
		} else if (id == R.id.login_backGame) {
			GuanSDK.instance.clickBackGame();
		} else {
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			GuanSDK.instance.clickBackGame();
		}
		return true;
	}
	
	public interface ClickBackGameCallBack{
		public void clickBackGame();
	}
	
	/**
	 * 正常登录
	 */
	public void normalLogin(){
		//发送到服务器进行校验
		//需要异步
		boolean checkResult =  simpleValidate();
		if(checkResult){
			final Handler registerHandler = new Handler(){
				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					String message = msg.getData().getString("errorMessage");
					if(!message.equals("")){
						Toast.makeText(LoginActivity.this, message,Toast.LENGTH_SHORT).show();
					}
				}
			};
			final ProgressDialog dialog = Util.showProgressDialog(this,"正在登录");
			new Thread(){
				public void run() {
					StringBuilder params = new StringBuilder();
					params.append("?userAccount="+getUserAccount());
					params.append("&password="+getPassword());
					params.append("&actionCode="+KomSDKInfo.ACTION_CODE_LOGIN);
					String result  = Util.getWebCon((GuanSDK.debug?GuanSDK.LOGINURL_DEBUG:GuanSDK.LOGINURL)+params.toString());
					Object odata = Util.decodeJson(result, KomLoginResponseData.class);
					dialog.dismiss();
					if(odata!=null){
						KomLoginResponseData kdata = (KomLoginResponseData) odata;
						if(kdata.getCode()==1){
							//保存帐号密码
							saveUserInfo();
							
							//返回登录结果
							Intent it = getIntent();
							it.putExtra("loginResult", true);
							it.putExtra("userAccount", kdata.getUserAccount());
							it.putExtra("time", kdata.getTime());
							it.putExtra("sign", kdata.getSign());
							LoginActivity.this.finish();
							
						}else{
							Message msg = new Message();
							Bundle errorData = new Bundle();
							errorData.putString("errorMessage", kdata.getErrorDesc());
							msg.setData(errorData);
							registerHandler.sendMessage(msg);
						}
					}else{
						Message msg = new Message();
						Bundle errorData = new Bundle();
						errorData.putString("errorMessage", "连接服务器失败请重试");
						msg.setData(errorData);
						registerHandler.sendMessage(msg);
					}
				};
			}.start();
		}
	}
	
	
	/**
	 * 简单校验  
	 * @return
	 */
	public boolean simpleValidate(){
		boolean result = false;
		String userAccountErrorMsg = "";
		String passwordErrorMsg = "";
		String userAccount = getUserAccount();
		String password = getPassword();
		
		//帐号
		if(userAccount==null){
			userAccountErrorMsg="帐号不能为空";
		}else{
			if(userAccount.length()<6&&userAccount.length()<11){
				userAccountErrorMsg="帐号长度必须由6到10位数字或字母组成";
			}else{
				if(!validateUserAccount(userAccount)){
					userAccountErrorMsg="帐号只能包含数字和字母";
				}
			}
		}
		if(!userAccountErrorMsg.equals("")){
			tv_msg_userAccount.setText(userAccountErrorMsg);
			refreshErrorMsgTV(tv_msg_userAccount,true);
		}else{
			tv_msg_userAccount.setText("");
			refreshErrorMsgTV(tv_msg_userAccount,false);
		}
		
		//密码
		if(password==null){
			passwordErrorMsg="密码不能为空";
		}else{
			if(password.length()<6&&password.length()<11){
				passwordErrorMsg="密码长度必须由6到10位数字或字母组成";
			}else{
				if(!validateUserAccount(password)){
					passwordErrorMsg="密码只能包含数字和字母";
				}
			}
		}
		if(!passwordErrorMsg.equals("")){
			tv_msg_password.setText(passwordErrorMsg);
			refreshErrorMsgTV(tv_msg_password,true);
		}else{
			tv_msg_password.setText("");
			refreshErrorMsgTV(tv_msg_password,false);
		}
		if(passwordErrorMsg.equals("")&&userAccountErrorMsg.equals("")){
			result = true;
		}
		return result;
	}
	
	/**
	 * 刷新校验错误信息文本
	 */
	public void refreshErrorMsgTV(final TextView tv,boolean show){
		if(!show){
			if(tv.getVisibility()!=VISIBLE_GONE){
				Animation animation = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
				animation.setAnimationListener(new AnimationListener() {
					@Override
					public void onAnimationStart(Animation animation) {
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						tv.setVisibility(VISIBLE_GONE);
					}
				});
				tv.startAnimation(animation);
			}
		}else{
			if(tv.getVisibility()!=VISIBLE_VISIBLE){
				tv.setVisibility(VISIBLE_VISIBLE);
				Animation animation = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
				tv.startAnimation(animation);
			}
		}
	}
	
	/**
	 * 校验帐号格式
	 * @param userAccount
	 * @return
	 */
	public boolean validateUserAccount(String userAccount){
		boolean result = false;
		String regx = "[a-zA-Z0-9]*";
		result=userAccount.matches(regx);
		return result;
	}
	
	
	/**
	 * 跳转到注册界面
	 */
	public void goRegister(){
		Intent it = new Intent(this, RegisterActivity.class);
		this.startActivityForResult(it, KomSDKInfo.RESULT_CODE_REGISTER);
	}
	
	
	/**
	 * 保存用户数据
	 */
	public void saveUserInfo(){
		boolean savePwd = cb_savePwd.isChecked();
		SharedPreferences userInfo = getSharedPreferences("kom_ol_userInfo", 0); 
		Editor userInfoEditor = userInfo.edit();
		if(savePwd){
			 String userAccount = getUserAccount();
			 String password = getPassword();
			 if(userAccount!=null&&password!=null){
				 userInfoEditor.putString("userAccount", userAccount);
				 userInfoEditor.putString("password",encodePassword(password));
				 userInfoEditor.putBoolean("savePassword", true);
			 }
		}else{
			userInfoEditor.remove("userAccount");
			userInfoEditor.remove("password");
			userInfoEditor.remove("savePassword");
		}
		userInfoEditor.commit();
	}
	
	public String getUserAccount(){
		 String userAccount = et_userAccount.getText().toString();
		 if(userAccount!=null&&!userAccount.trim().equals("")){
			 return userAccount;
		 }
		 return null;
	}
	
	public String getPassword(){
		 String password = et_pwd.getText().toString();
		 if(password!=null&&!password.trim().equals("")){
			 return password;
		 }
		 return null;
	}
	
	
	/**
	 * 解密密码
	 * @param loginKey
	 * @return
	 */
	private static String decodePassword(String loginKey){
		byte[] decodeBytes=null;
		try {
			decodeBytes = Base64.decode(loginKey);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		decodeBytes[0]=(byte) (~decodeBytes[0]-byteFix[0]);
		decodeBytes[decodeBytes.length-1]=(byte) (~decodeBytes[decodeBytes.length-1]-byteFix[1]);
		String decodeValue = new String(decodeBytes);
		decodeValue=decodeValue.replace(","+key, "");
		return decodeValue;
	}
	
	/**
	 * 加密密码
	 * @param loginKey
	 * @return
	 */
	private static String encodePassword(String password){
		//帐号+时间+登录平台
		password=password+","+key;
		byte[] keyByte = password.getBytes();
		keyByte[0]=(byte) ~(keyByte[0]+byteFix[0]);
		keyByte[keyByte.length-1]=(byte) ~(keyByte[keyByte.length-1]+byteFix[1]);
		String encodedValue = Base64.encode(keyByte);
		return encodedValue;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		switch (requestCode) {
		case KomSDKInfo.RESULT_CODE_REGISTER:
			if(data.getExtras()==null||!data.getExtras().containsKey("registerResult")){
				Toast.makeText(this, "取消注册", Toast.LENGTH_SHORT).show();
			}else{
				Bundle resultParams = data.getExtras();
				boolean registerResult = resultParams.getBoolean("registerResult");
				if(registerResult){
					Toast.makeText(this, "创建帐号成功", Toast.LENGTH_SHORT).show();
					String userAccount = resultParams.getString("userAccount");
					String password = resultParams.getString("password");
					String sign = resultParams.getString("sign");
					int time = resultParams.getInt("time");
					et_pwd.setText(password);
					et_userAccount.setText(userAccount);
					cb_savePwd.setChecked(true);
					saveUserInfo();
					
					//注册登录成功
					Intent it = getIntent();
					it.putExtra("loginResult", true);
					it.putExtra("userAccount", userAccount);
					it.putExtra("time", time);
					it.putExtra("sign", sign);
					
					final ProgressDialog dialog = Util.showProgressDialog(this,"正在登录");
					new Thread(){
						@Override
						public void run() {
							super.run();
							try {
								sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							dialog.dismiss();
							LoginActivity.this.finish();
						}
					}.start();
				}
			}
			break;
		default:
			break;
		}
	}
	
}
